foreach y of numlist 2005(1)2019 {
	global y `y'
	use ${condDADS} using "${tmp}/dads${y}", clear
	
	destring catjur*, replace
	// drop Particuliers employeurs
	drop if inlist(substr(string(catjur),1,1),"1","2","3","5","6")  == 1 & substr(siren,1,1)=="P"
	drop if inlist(substr(string(catjur_1),1,1),"1","2","3","5","6")  == 1 & substr(siren,1,1)=="P"

	keep if (floor(catjur/1000)==5) // keep private
	
	replace apet = apen if mi(apet)
	
	gen hskill = substr(pcs,1,1)=="3"
	gen job_eng = (substr(pcs,1,2) == "38")
	gen job_tech = (substr(pcs,1,2) == "47")
	
	gen nbheur_eng = nbheur*job_eng
	gen nbheur_tech = nbheur*job_tech
	gen nbheur_hskill = nbheur*hskill
	
	gen dep = substr(comt,1,2)
	bys siren dep: egen com_mod = mode(comt), minmode
	replace comt = com_mod if mi(comt)
	drop com_mod
	replace comt = substr(comr,1,2) if mi(comt)
	
	*encode apet, gen(apet_num)
	
	bys siren comt (apet): replace apet = apet[1] 
	bys siren comt (catjur): replace catjur = catjur[1]
	collapse (sum) hskill job_tech job_eng nbheur_eng nbheur_tech nbheur_hskill nbheur_tot = nbheur (firstnm) apet apen catjur comr , by(siren comt)
	
	ren apet ape
	gen year = ${y}
	
	destring siren , force replace
	drop if mi(siren)
		
	save "${tmp}/sirencom_dads_${y}", replace
}

tempfile main
clear 
foreach y of numlist 2005(1)2019 {
	global y `y'
	use "${tmp}/sirencom_dads_${y}", clear
	
	ren ape apet
	replace apet = apen if mi(apet)
	
	if `y'<=2007 {
		ren apet naf_rev1
		merge m:1 siren using "${data}/Utils/Siren_NAF_rev12", nogen keep(1 3) keepusing(naf_rev2)
		merge m:1 naf_rev1 using "${data}/Utils/NAF_rev12_impute", nogen keep(1 3 4 5) update  keepusing(naf_rev2)
		drop naf_rev1
		ren naf_rev2 apet
		
		
		ren apen naf_rev1
		merge m:1 siren using "${data}/Utils/Siren_NAF_rev12", nogen keep(1 3) keepusing(naf_rev2)
		merge m:1 naf_rev1 using "${data}/Utils/NAF_rev12_impute", nogen keep(1 3 4 5) update  keepusing(naf_rev2)
		drop naf_rev1
		ren naf_rev2 apen
		}
	cap append using `main'
	
	save `main', replace
		
}
compress
save "${tmp}/sirencom_dads_0519", replace


use "${tmp}/sirencom_dads_0519", clear
gen depcom = comt
replace depcom = "75056" if substr(depcom,1,2) == "75"
replace depcom = "13055" if inrange(real(depcom),13201,13216)
replace depcom = "69123" if inrange(real(depcom),69381,69389)
replace depcom = "59183" if depcom == "59540" | depcom == "59248"
destring depcom, replace force
drop if mi(depcom)
merge m:1 depcom using "${data}/Utils/depcom_ZE_mapping", nogen keep(1 3)

collapse (sum) hskill job_eng job_tech nbheur_eng nbheur_tech nbheur_hskill nbheur_tot (firstnm) apet apen catjur , by(siren ZE2010 year)

save "${data}/Utils/sirenZE_dads_0519", replace
